﻿using Furion;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using net8.Models;
using net8.Models.Upload;
using net8.Views;

namespace net8.Controllers.XiTong
{
    /// <summary>
    /// 上传管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    public class UploadController : ControllerBase
    {
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file">文件对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<UploadFile> Upload(IFormFile file)
        {
            string root = App.WebHostEnvironment.WebRootPath;
            string formatPath = "/UploadFiles/" + DateTime.Today.ToString("yyyyMMdd") + "/";
            string path = root + formatPath;

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }

            string fileName = Guid.NewGuid().ToString("N") + System.IO.Path.GetExtension(file.FileName);

            string savePath = path + fileName;

            using (var stream = System.IO.File.Create(savePath))
            {
                await file.CopyToAsync(stream);
            }

            UpFile model = new UpFile()
            {
                Id = Guid.NewGuid(),
                FileName = file.FileName,
                FilePath = formatPath + fileName,
                IsDel = false,
                UpdateTime = DateTime.Now,
                AddTime = DateTime.Now
            };
            await DbHelper.Db.Insertable(model).ExecuteCommandAsync();

            return new UploadFile() { Id = model.Id, Url = formatPath + fileName };
        }
    }
}
